import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/pinia/modules/user'
import { useRouterStore } from '@/pinia/modules/router'
import { dictStore } from '@/pinia/modules/dict'
import Nprogress from 'nprogress'

const whiteList = ['Login', 'demo', 'Plat']
const routes = [{
  path: '/',
  redirect: '/login'
},
{
  path: '/login',
  name: 'Login',
  component: () => import('@/view/login/index.vue')
},
// {
//   path: '/demo',
//   name: 'demo',
//   component: () => import('@/view/demo/index.vue')
// },
{
  path: '/plat',
  name: 'Plat',
  component: () => import('@/view/login/plat.vue')
},
{
  path: '/home',
  name: 'Home',
  component: () => import('@/view/home/index.vue')
},
{
  path: '/loading',
  name: 'loading',
  component: () => import('@/view/loading/index.vue')
},
{
  path: '/:catchAll(.*)',
  hidden: true,
  component: () => import('@/view/error/index.vue')
},

]

const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior: () => ({ x: 0, y: 0 }),
  routes
})

// 添加路由
const getRouter = async userStore => {
  let res = await useRouterStore().SetAsyncRouter()
  useRouterStore().asyncRouters.allRoutes.forEach(asyncRouter => {
    router.addRoute(asyncRouter)
  })
  return res
}

router.beforeEach(async (to, from, next) => {
  Nprogress.start()
  const userStore = useUserStore()
  const token = userStore.token
  if (token) {
    if (whiteList.indexOf(to.name) != -1) {
      next()
      Nprogress.done()
    } else {
      const routes = JSON.parse(JSON.stringify(useRouterStore().asyncRouters.allRoutes))
      // 判断是否存储后台路由
      if (routes && routes.length > 0) {
        next()
      } else {
        // 添加路由
        let routerRes = await getRouter(userStore)
        // 添加字典
        await dictStore().getDict()
        // await appCurrentState().SET_WAIT_LIST()
        if (routerRes) {
          next({
            ...to,
            replace: true
          })
        } else {
          next()
          Nprogress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.name) != -1) {
      next()
      Nprogress.done()
    } else {
      next(`/login`)
      Nprogress.done()
    }
  }
})

router.afterEach(() => {
  // 路由加载完成后关闭进度条
  Nprogress.done()
})

router.onError(() => {
  // 路由发生错误后销毁进度条
  Nprogress.remove()
})

export default router
